//
//  AdvisoryViewModel.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/2/10.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import HandyJSON

enum AdvisoryStatus: Int {
    case notDiagnosed
    case diagnosing
    case endDiagnosed
    case rejected = 5
    case unknow = -1
}

struct Advisory: HandyJSON {
    /// 医生id
    var doctorId: String?
    /// 医生姓名
    var doctorName: String?
    /// 科室名称
    var deptName: String?
    /// 医生职称
    var jobTitle: String?
    /// 医生头像
    var picture: String?
    var pictureId: String?
    /// 最后一条消息
    var content: String?
    /// 最后一条消息发送事件
    var sendTime: String?
    var msgId: String?
    /// 诊断id
    var diagnoseId: String?
    /// 诊断状态: 0-未诊断 1-诊断中 2-已结束
    var flag: Int = 0
    /// 记录发送者类型: 0-患者 1-医生
    var fromType: Int = -1
    /// 未读消息数量
    var unreadCount: Int = 0
    var messageType: Int = 0
    
    /// 诊断是否置顶  1-置顶  0-不置顶
    var doctorIsTop: Int = 0
    
    // 咨询 或者 复诊
    var businessType : Int = 0
}

struct AdvisoryViewModel {
    var models: [Advisory]
    
    /// 显示空白页面
    var showEmptyView: Bool { return models.count <= 0 }
    
    var numberOfRows: Int { return models.count }
    
    func viewModel(of indexPath: IndexPath) -> RowViewModel {
        return RowViewModel(advisory: models[indexPath.row])
    }
    
    mutating func loadMore(with models: [Advisory]) {
        self.models += models
    }
    
    struct RowViewModel {
        let advisory: Advisory
        
        /// 诊断id
        var diagnoseId: String { return advisory.diagnoseId ?? "" }
        
        var avatar: String { return advisory.picture ?? "" }
        /// 医生姓名
        var doctor: String { return advisory.doctorName ?? "" }
        /// 医生id
        var doctorId: String { return advisory.doctorId ?? ""}
        /// 科室
        var department: String { return advisory.deptName ?? "" }
        /// 职位
        var office: String { return advisory.jobTitle ?? "" }
        /// 未读数
        var unreadCount: String { return "\(advisory.unreadCount)" }
        
        var isHiddenUnread: Bool { return advisory.unreadCount <= 0 }
        
        var businessType: Int { return advisory.businessType }
        
        /// 图文咨询状态
        var status: AdvisoryStatus { return AdvisoryStatus(rawValue: advisory.flag) ?? .unknow }
        /// 最后一条消息内容
        var lastMsg: String {
            switch msgType {
            case .image: return "[图片]"
            case .voice: return "[语音]"
            case .video: return "[视频]"
            case .music: return "[音乐]"
            case .news: return "[新闻]"
            case .prescription: return "[处方]"
            default: return (advisory.content?.isEmpty ?? true) ? "无沟通记录" : (advisory.content ?? "")
            }
        }
        
        var msgType: ChatMsgType { return ChatMsgType(rawValue: advisory.messageType) ?? .text }
        
        var lastMsgTime: String { return advisory.sendTime ?? "" }
        
        /// 诊断是否置顶  1-置顶  0-不置顶
        var doctorIsTop: Int { return advisory.doctorIsTop }
        
        var msgIsTop: Int { return doctorIsTop == 1 ? 0 : 1 }
        var msgIsTopEdit: String { return doctorIsTop == 1 ? "取消置顶" : "置顶聊天" }
        
        var cellHeight: CGFloat { return 110 }
    }
}

extension AdvisoryViewModel {
    static func getAdvisotyList(patientId: Int,
                                current: Int,
                                success: @escaping (_ models: [Advisory]) -> Void,
                                failure: @escaping (_ errorMsg: String?) -> Void) {
        let paras: [String: Any] = [
            "patientUserId": patientId,
            "current": current,
            "size": 10
        ]
        HttpTool.shared.request(target: ApiManager.advisoryList(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let models = JSONDeserializer<Advisory>.deserializeModelArrayFrom(json: json["data"]["records"].description) as? [Advisory] {
                    success(models)
                } else {
                    failure("请求数据发生错误，稍候重试！")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    static func getNurseList(patientId: Int,
                                current: Int,
                                success: @escaping (_ models: [Advisory]) -> Void,
                                failure: @escaping (_ errorMsg: String?) -> Void) {
        let paras: [String: Any] = [
            "patientUserId": patientId,
            "current": current,
            "size": 10
        ]
        HttpTool.shared.request(target: ApiManager.nurseList(paras: paras), success: { (json, code) in
            switch code {
            case .failure:
                failure(json["message"].description)
            case .success:
                if let models = JSONDeserializer<Advisory>.deserializeModelArrayFrom(json: json["data"]["records"].description) as? [Advisory] {
                    success(models)
                } else {
                    failure("请求数据发生错误，稍候重试！")
                }
            }
        }) { errorMsg in
            failure(errorMsg)
        }
    }
    /// 确认是否结束咨询
    static func endAdvisory(doctorId: String,
                            diagnoseId: String,
                            isSure: Int,
                            finished: @escaping (_ errorMsg: String?, _ code: HttpCode) -> Void)
    {
        let paras: [String: Any] = [
            "doctorUserId": doctorId,
            "diagnoseId": diagnoseId,
            "status": isSure
        ]
        HttpTool.shared.request(target: ApiManager.endAdvisory(paras: paras), success: { (json, code) in
            finished(json["message"].description, code)
        }) { errorMsg in
            finished(errorMsg, .failure)
        }
    }
    
    
    /// 确认是否结束咨询
    static func endNurse(diagnoseId: String,
                         isRefuse: Int,
                            finished: @escaping (_ errorMsg: String?, _ code: HttpCode) -> Void)
    {
        let paras: [String: Any] = [
            "diagnoseId": diagnoseId,
            "isRefuse": isRefuse
        ]
        HttpTool.shared.request(target: ApiManager.endNurse(paras: paras), success: { (json, code) in
            finished(json["message"].description, code)
        }) { errorMsg in
            finished(errorMsg, .failure)
        }
    }
    
    
    /// 图文咨询置顶和取消
    /// status: 诊断是否置顶  1-置顶  0-不置顶
    /// userType: 0-患者端设置置顶  1-医生端设置置顶
    static func advisoryIsTop(diagnoseId: String,
                              status: Int,
                              userType: Int = 0,
                              finished: @escaping (_ errorMsg: String?, _ code: HttpCode) -> Void) {
        let paras: [String: Any] = ["diagnoseId": diagnoseId, "status": status, "userType": userType]
        HttpTool.shared.request(target: ApiManager.advisoryIsTop(paras: paras), success: { (json, code) in
            finished(json["message"].description, code)
        }) { errorMsg in
            finished(errorMsg, .failure)
        }
    }
}
